#include "SimpleButton.hpp"
#include "SDL_ttf.h"

SimpleButton::SimpleButton() {
    x = y = w = h = 0;

    cursor_downed = false;
    clicked = false;
    
    app_state = 0;
    button_state = 1;
    ::set_color(color1, 200, 200, 200, 200);
    ::set_color(color2, 180, 180, 180, 200);
    ::set_color(color3, 160, 160, 160, 200);
}

SimpleButton::~SimpleButton()
{
}

void SimpleButton::init(AppState* app_state, const char* text) {
    this->app_state = app_state;
    img_text.app_state = app_state;
    img_text.create_text(text);
}


#define is_in_box ((event.button.x >= x && event.button.x <= x+w && event.button.y >= y && event.button.y <= y+h) \
                   || (event.tfinger.x*app_state->display_mode.w >= x && event.tfinger.x*app_state->display_mode.w <= x+w && event.tfinger.y*app_state->display_mode.h >= y && event.tfinger.y*app_state->display_mode.h <= y+h))
void SimpleButton::handle(const SDL_Event& event) {
    if ((event.type == SDL_MOUSEBUTTONUP || event.type == SDL_FINGERUP) && is_in_box && cursor_downed)
        clicked = true;
    else
        clicked = false;

    if ((event.type == SDL_MOUSEBUTTONUP || event.type == SDL_FINGERUP) && is_in_box) {
        cursor_downed = false;
        button_state = 1;
    } else if ((event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_FINGERDOWN) && is_in_box) {
        cursor_downed = true;
        button_state = 3;
    } else if ((event.type == SDL_MOUSEMOTION || event.type == SDL_FINGERMOTION) && is_in_box) {
        cursor_downed = false;
        button_state = 2;
    } else {
        cursor_downed = false;
        button_state = 1;
    }
}

void SimpleButton::update() {
}

void SimpleButton::draw() {
    SDL_Rect rect = { x, y, w, h };
    switch (button_state) {
        case 1:
            SDL_SetRenderDrawColor(app_state->renderer, color1.r, color1.g, color1.b, color1.a);
            break;
        case 2:
            SDL_SetRenderDrawColor(app_state->renderer, color2.r, color2.g, color2.b, color2.a);
            break;
        case 3:
            SDL_SetRenderDrawColor(app_state->renderer, color3.r, color3.g, color3.b, color3.a);
            break;
    }
    SDL_RenderFillRect(app_state->renderer, &rect);

    float s = 0.9;
    img_text.w = w*s;
    img_text.h = h*s;
    img_text.x = x+w*(1-s)/2;
    img_text.y = y+h*(1-s)/2;
    img_text.draw();
}
